package com.eight.cloud.excel.listener;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.idev.excel.context.AnalysisContext;
import cn.idev.excel.event.AnalysisEventListener;
import cn.idev.excel.exception.ExcelDataConvertException;
import cn.idev.excel.metadata.Cell;
import cn.idev.excel.metadata.data.CellData;
import cn.idev.excel.metadata.data.WriteCellData;
import cn.idev.excel.read.metadata.holder.ReadRowHolder;
import com.eight.cloud.excel.model.Message;
import com.eight.cloud.excel.model.VerificationFailRow;
import com.eight.cloud.excel.validated.FastExcelValidHelper;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName: DataListener
 * @Author: TXC
 * @Date: 2025-08-08 17:21
 **/
@Getter
@Slf4j
public class DataListener<T> extends AnalysisEventListener<T> {
    private final List<T> rows = new ArrayList<>();
    private final List<VerificationFailRow<?>> verifyFails = new ArrayList<>();
    private final List<VerificationFailRow<?>> convertFails = new ArrayList<>();

    @Override
    public void invoke(T bean, AnalysisContext analysisContext) {
        String errMsg = FastExcelValidHelper.validateEntity(bean);
        if (StrUtil.isBlank(errMsg)) {
            rows.add(bean);
        } else {
            verifyFails.add(new VerificationFailRow<>(bean, new Message(errMsg)));
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        log.info("解析完成！读取成功{}行，读取失败{}行", rows.size(), verifyFails.size() + convertFails.size());
    }

    @Override
    public void onException(Exception exception, AnalysisContext context) {
        if (exception instanceof ExcelDataConvertException) {
            ExcelDataConvertException convertException = (ExcelDataConvertException) exception;
            String errMsg = String.format("原数据表第%s行，第%s列，数据：%s，解析异常！",
                    convertException.getRowIndex(), convertException.getColumnIndex() + 1, getCellData(convertException.getCellData()));
            log.error("{}{}", errMsg, String.format("异常信息 =》 %s", exception.getMessage()));
            ReadRowHolder readRowHolder = context.readRowHolder();
            Map<Integer, Cell> cellMap = readRowHolder.getCellMap();
            Map<Integer, WriteCellData<?>> rowData = writeMapToExcel(cellMap);
            convertFails.add(new VerificationFailRow<>(rowData, new Message(errMsg)));
        } else {
            log.error("解析失败，继续解析下一行:{}", exception.getMessage());
        }
    }

    private Map<Integer, WriteCellData<?>> writeMapToExcel(Map<Integer, Cell> cellMap) {
        Map<Integer, WriteCellData<?>> map = new HashMap<>();
        cellMap.forEach((key, value) -> map.put(key, BeanUtil.copyProperties(value, WriteCellData.class)));
        return map;
    }

    private Object getCellData(Cell cell) {
        CellData<?> cellData = (CellData<?>) cell;
        switch (cellData.getType()) {
            case EMPTY : return StrUtil.EMPTY;
            case BOOLEAN : return cellData.getBooleanValue();
            case NUMBER : return cellData.getNumberValue();
            default : return cellData.getStringValue();
        }
    }
}
